package com.xxl.job.admin.service;

import com.xxl.job.admin.controller.JobResultController;
import com.xxl.job.admin.dto.JobResultDTO;
import org.springframework.stereotype.Service;

/**
 * @author wenhonghao
 * @email 18167784149@163.com
 * @description: 封装等待执行器回调的通用方法
 */
@Service
public class JobResultService {
    private final JobResultController jobResultController;

    public JobResultService(JobResultController jobResultController) {
        this.jobResultController = jobResultController;
    }

    /**
     * 等待执行器的回调结果
     *
     * @param serverIp   执行器的IP地址
     * @param maxRetries 最大重试次数
     * @param waitTime   每次等待的时间，单位毫秒
     * @return 执行器回调结果（JobResultDTO），可能为 null 表示超时
     */
    public JobResultDTO waitForExecutionResult(String serverIp, int maxRetries, long waitTime) {
        JobResultDTO jobResultDTO = null;
        int retryCount = 0;
        jobResultController.clearExecutionResult(serverIp);
        while (retryCount < maxRetries) {
            jobResultDTO = jobResultController.getLastExecutionResult(serverIp);
            if (jobResultDTO != null) {
                break;
            }
            retryCount++;
            try {
                Thread.sleep(waitTime);  // 等待执行器回调
            } catch (InterruptedException e) {
                Thread.currentThread().interrupt();
                System.err.println("线程中断错误: " + e.getMessage());
                return null;
            }
        }


        return jobResultDTO;
    }
}
